package com.webserver_v5.core;

import com.webserver_v5.annotation.Controller;
import com.webserver_v5.annotation.RequestMapping;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {
    private static Map<String, Method>mapping = new HashMap<>();
    private static File rootDir;

    static {
        initMapping();
    }
   private static void initMapping(){
       try {
           rootDir = new File(HandlerMapping.class.getClassLoader()
                   .getResource(".").toURI());
           File dir = new File(rootDir,"com/webserver_v5/controller");
           if (dir.exists()){
               File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
               for (File sub:subs){
                   String className = sub.getName().replace(".class","");
                   Class cls = Class.forName("com.webserver_v5.controller."+className);
                   if (cls.isAnnotationPresent(Controller.class)){
                       Method[] methods = cls.getDeclaredMethods();
                       for (Method method : methods){
                           if (method.isAnnotationPresent(RequestMapping.class)){
                               RequestMapping rm = method.getAnnotation(RequestMapping.class);
                               String value = rm.value();
                               mapping.put(value,method);
                           }
                       }
                   }
               }
           }
       } catch (URISyntaxException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
   }
   public static Method getMethod(String uri){
        return mapping.get(uri);
   }
}
